package cn.itcast.usercontext.interceptor;

import cn.itcast.usercontext.common.ResponseResult;
import cn.itcast.usercontext.util.usersession.LoginUser;
import cn.itcast.usercontext.util.usersession.UserContext;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author sxt
 * @version 1.0
 * @description TODO
 * @date 2024/4/25 21:01
 */
public class UserLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LoginUser loginUser = UserContext.get();
        if (loginUser != null) {
            return true;
        }
        // 判断对应访问的handler是否需要做登录拦截
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        LoginCheck annotation = handlerMethod.getBean().getClass().getAnnotation(LoginCheck.class);
        if (annotation == null) {
            annotation = handlerMethod.getMethodAnnotation(LoginCheck.class);
        }
        NoLoginCheck methodAnnotation = handlerMethod.getMethodAnnotation(NoLoginCheck.class);
        if (annotation == null || methodAnnotation != null) {
            // 放行
            return true;
        }

        doErrorResponse(response, "用户未登录");
        return false;
    }

    private void doErrorResponse(HttpServletResponse response, String msg) throws IOException {
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().println(JSONObject.toJSONString(ResponseResult.error(msg)));
    }
}
